var express = require('express');
var router = express.Router();
var User = require('./../model/user');
//excel
var ejsExcel = require("ejsExcel");
var fs = require("fs");
var exlBuf = fs.readFileSync("./server/excel/modal/hc.xlsx");

/* GET users listing. */
function isEmpty(obj) {
  if (typeof obj == "undefined" || obj == null || obj == "") {
    return true;
  } else {
    return false;
  }
}

router.get('/', function (req, res, next) {
  res.send('respond with a resource');
});
//登录
router.post('/login', (req, res, next) => {
  var account = req.body.account;
  var password = req.body.password;
  User.findOne({account, password}, (err, userDoc) => {
    if (err) {
      res.json({
        status: '0',
        msg: err.message,
        result: ''
      })
    } else {
      if (userDoc) {
        //存在cookie里
        var token = userDoc.userName + '-' + userDoc.userId;
        res.cookie("token", token, {
          path: '/',
          maxAge: 1000 * 60 * 60
        });
        res.json({
          status: '1',
          msg: 'suc',
          result: userDoc.userName
        })
      } else {
        res.json({
          status: '0',
          msg: '用户名或密码错误',
          result: ''
        })
      }
    }
  })

});
//登出
router.post('/logout', (req, res, next) => {
  res.cookie('token', '', {
    path: '/',
    maxAge: -1
  });
  res.json({
    status: "1",
    msg: 'suc',
    result: 'logout success'
  })
});
//页面重新刷新时判断是否为登录状态
router.post('/isLogin', (req, res, next) => {
  var token = req.cookies.token;
  //如果token为undefined
  if (token === undefined) {
    res.json({
      status: '0',
      msg: '没有登录',
      result: ''
    })
  }else {
    //截取token变成userName还有userId
    var middle = token.indexOf('-');
    var userName = token.slice(0, middle);
    var userId = token.slice(middle + 1);
    //在数据库中查找是否存在这个用户
    User.findOne({userName, userId}, (err, userDoc) => {
      if (err) {
        res.json({
          status: '0',
          msg: err.message(),
          result: ''
        })
      } else {
        if (userDoc) {
          res.json({
            status: '1',
            msg: 'suc',
            result: userDoc.userName
          })
        } else {
          res.json({
            status: '0',
            msg: '没有此用户',
            result: ''
          })
        }
      }
    })
  }
});
//查询用户信息
router.post('/queryUser', (req, res, next) => {
  var queryForm = req.body.queryForm;
  var queryResult;
  if (isEmpty(queryForm.userId) && !isEmpty(queryForm.userName)) {
    queryResult = User.find({userName: queryForm.userName, isConf: queryForm.isConf})
  } else if (!isEmpty(queryForm.userId) && isEmpty(queryForm.userName)) {
    queryResult = User.find({userId: queryForm.userId, isConf: queryForm.isConf})
  } else if (isEmpty(queryForm.userId) && isEmpty(queryForm.userName)) {
    queryResult = User.find({isConf: queryForm.isConf})
  } else {
    queryResult = User.find({userName: queryForm.userName, userId: queryForm.userId, isConf: queryForm.isConf})
  }
  queryResult.exec((err, docs) => {
    if (err) {
      res.json({
        status: '0',
        msg: err.message,
        result: ''
      })
    } else {
      if (docs) {
        res.json({
          status: '1',
          msg: 'suc',
          result: docs
        })
      } else {
        res.json({
          status: '0',
          msg: 'user is not found',
          result: ''
        })
      }
    }
  })

})
//更改角色
router.post('/modifyRole', (req, res, next) => {
  var user = req.body.user;
  /* User.findOne({userId: user.userId},(err,userDoc)=>{
     if (err){
       res.json({
         status: '0',
         msg: err.message,
         result: ''
       })
     } else {
       if (userDoc){
         userDoc.roleName=user.roleName;
         userDoc.save((err1,doc1)=>{
           if (err1){
             res.json({
               status: '0',
               msg: err1.message,
               result: ''
             })
           } else {
             res.json({
               status: '1',
               msg: 'suc',
               result: doc
             })
           }
         });
       } else {
         res.json({
           status: '0',
           msg: 'user is not found',
           result: ''
         })
       }
     }
   })*///另一种方法
  User.update({userId: user.userId},
    {$set: {roleName: user.roleName}},
    (err, doc) => {
      if (err) {
        res.json({
          status: '0',
          msg: err.message,
          result: ''
        })
      } else {
        res.json({
          status: '1',
          msg: 'suc',
          result: doc
        })
      }
    })
});
//生成excel模板
router.post('/getExcel', (req, res, next) => {
  let excelData = req.body.excelData;
  ejsExcel.renderExcel(exlBuf, excelData).then(function (exlBuf2) {//exlBuf2为渲染成功的模板
    fs.writeFileSync("./server/excel/products/hc_text.xlsx", exlBuf2);
    console.log("生成渲染成功！");
    res.json({
      status: '1',
      msg: 'suc',
      result: ''
    })
  }).catch(function (err) {
    res.json({
      status: '0',
      msg: 'failed',
      result: ''
    })
    console.error(err);
  });
});
//获取Excel模板
router.get('/export',(req,res,next)=>{
  //文件下载
  /*fs.readFile("./server/excel/products/hc_text.xlsx", function (isErr, data) {
    if (isErr) {
      res.end("Read file failed!");
      return;
    }
    res.writeHead(200, {
      'Content-Type': 'application/octet-stream', //告诉浏览器这是一个二进制文件
      'Content-Disposition': 'attachment; filename=' + 'hc_text.xlsx', //告诉浏览器这是一个需要下载的文件
    });
    res.end(data)
  })*/
  /*res.writeHead(200,{
    'Content-Type': 'application/octet-stream', //告诉浏览器这是一个二进制文件
    'Content-Disposition': 'attachment; filename=' + 'hc_text.xlsx', //告诉浏览器这是一个需要下载的文件
  });
  fs.createReadStream("./server/excel/products/hc_text.xlsx").pipe(res);*/
  res.download("./server/excel/products/hc_text.xlsx",'hc.xlsx')
})
module.exports = router;
